//
//  XRPlayerViewController.m
//  avplayer
//
//  Created by 谢汝 on 2017/12/18.
//  Copyright © 2017年 谢汝. All rights reserved.
//

#import "XRPlayerViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "XRProgressSlider.h"
#import "XRPlayerView.h"

@interface XRVideoModel ()

@end


@implementation XRVideoModel

- (instancetype)initWithName:(NSString *)name url:(NSURL *)url {
    if (self = [super init]) {
        _name = name;
        _url = url;
    }
    return self;
}
@end

@interface XRPlayerViewController ()

@property(nonatomic,strong)AVPlayer *avPlayer;
@property(nonatomic,strong)AVPlayerItem *avPlayerItem;
@property(nonatomic,strong)AVPlayerLayer *avPlayerLayer;


@property(nonatomic,strong)UIView *topView;
@property(nonatomic,strong)NSLayoutConstraint *topCons;
@property(nonatomic,strong)UIButton *backBtn;
@property(nonatomic,strong)UILabel *titleLabel;
@property(nonatomic,strong)UITableView *listTableView;


@property(nonatomic,strong)UIView *bottomView;
@property(nonatomic,strong)NSLayoutConstraint *bottomCons;
@property(nonatomic,strong)UIButton *playBtn;
@property(nonatomic,strong)UILabel *timeLabel;
@property(nonatomic,strong)XRProgressSlider *slider;


@property(nonatomic,strong)UIActivityIndicatorView *indictor;
@property(nonatomic,strong)CADisplayLink *link;
@property(nonatomic,assign)NSTimeInterval lastTime;

@property(nonatomic,assign)BOOL isHiddenTabView;
@property(nonatomic,assign)BOOL isHiddenListView;

@property(nonatomic,strong)UIView *failedView;



@property(nonatomic,strong)XRVideoModel *model;
@property(nonatomic,strong)NSArray<XRVideoModel *> *videoArray;
@end

@implementation XRPlayerViewController


- (instancetype)initWithVideoList:(NSArray<XRVideoModel *> *)videoList {
    NSAssert(videoList.count, @"The playlist can not be empty");
    if (self = [super init]) {
        self.videoArray = videoList;
        self.model = videoList[0];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self initPlayer];
    
    [self initSubviews];
}


- (void)initPlayer {
    self.avPlayerItem = [AVPlayerItem playerItemWithURL:self.model.url];
    [self addObserveWithPlayerItem:self.avPlayerItem];
    
    
    self.avPlayer = [AVPlayer playerWithPlayerItem:self.avPlayerItem];
    self.avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
    
    XRPlayerView *avPlayerView = [[XRPlayerView alloc]initWithMoviePlayerLayer:self.avPlayerLayer frame:self.view.bounds];
    avPlayerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:avPlayerView];
    
//    self.avPlayer addPeriodicTimeObserverForInterval:<#(CMTime)#> queue:<#(nullable dispatch_queue_t)#> usingBlock:<#^(CMTime time)block#>
    
    
    
    
}


- (void)initSubviews {
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.topView = [UIView new];
    self.topView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.5];
    [self.view addSubview:self.topView];
    self.topView.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self.topView.leftAnchor constraintEqualToAnchor:self.view.leftAnchor].active = YES;
    NSLayoutConstraint *topCons =[self.topView.topAnchor constraintEqualToAnchor:self.view.topAnchor constant:0];
    topCons.active = YES;
    [self.topView.rightAnchor constraintEqualToAnchor:self.view.rightAnchor].active = YES;
    [self.topView.heightAnchor constraintEqualToConstant:60].active = YES;
    
    self.backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backBtn setImage:[UIImage imageNamed:@"gobackBtn"] forState:UIControlStateNormal];
    [self.backBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.topView addSubview:self.backBtn];
    self.backBtn.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self.backBtn.leftAnchor constraintEqualToAnchor:self.topView.leftAnchor constant:10].active = YES;
    [self.backBtn.topAnchor constraintEqualToAnchor:self.topView.topAnchor constant:10].active = YES;
    [self.backBtn.bottomAnchor constraintEqualToAnchor:self.topView.bottomAnchor constant:-10].active = YES;
    [self.backBtn.widthAnchor constraintEqualToAnchor:self.backBtn.heightAnchor].active = YES;
    
    
    //标题
    self.titleLabel = [UILabel new];
    self.titleLabel.backgroundColor = [UIColor clearColor];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.text = self.model.name;
    [self.topView addSubview:self.titleLabel];
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.titleLabel.centerXAnchor constraintEqualToAnchor:self.topView.centerXAnchor].active = YES;
    [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.topView.centerYAnchor].active = YES;
    
    
    UIButton *listButton = [[UIButton alloc] initWithFrame:CGRectZero];
    [listButton setImage:[UIImage imageNamed:@"player_fit"] forState:UIControlStateNormal];
    [listButton addTarget:self action:@selector(showOrHideListTableViewAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.topView addSubview:listButton];
    listButton.translatesAutoresizingMaskIntoConstraints = NO;
    
    [listButton.rightAnchor constraintEqualToAnchor:self.topView.rightAnchor constant:-10].active = YES;
    [listButton.topAnchor constraintEqualToAnchor:self.topView.topAnchor constant:10].active = YES;
    [listButton.bottomAnchor constraintEqualToAnchor:self.topView.bottomAnchor constant:-10];
    [listButton.widthAnchor constraintEqualToAnchor:listButton.heightAnchor].active = YES;
    
    self.listTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
//    self.listTableView.delegate = self;
//    self.listTableView.dataSource = self;
    self.listTableView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.55];
    self.listTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.listTableView];
    
    [self.listTableView.rightAnchor constraintEqualToAnchor:self.view.rightAnchor constant:300].active = YES;
    [self.listTableView.topAnchor constraintEqualToAnchor:self.view.topAnchor constant:60].active = YES;
    [self.listTableView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor constant:-60].active = YES;
    [self.listTableView.widthAnchor constraintEqualToConstant:300].active = YES;
    
    
    self.bottomView = [UIView new];
    self.bottomView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.5];
    self.bottomView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.bottomView];
    
    [self.bottomView.leftAnchor constraintEqualToAnchor:self.view.leftAnchor].active = YES;
    [self.bottomView.rightAnchor constraintEqualToAnchor:self.view.rightAnchor].active = YES;
    [self.bottomView.heightAnchor constraintEqualToConstant:60].active = YES;
    self.bottomCons = [self.bottomView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor];
    self.bottomCons.active = YES;
    
    
    
    
}




- (NSTimeInterval)availableDurationWithPlayerItem:(AVPlayerItem *)playerItem {
    NSArray *loadedTimeRanges = playerItem.loadedTimeRanges;
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];
    NSTimeInterval startSeconds = CMTimeGetSeconds(timeRange.start);
    NSTimeInterval durationSeconds = CMTimeGetSeconds(timeRange.duration);
    return (startSeconds + durationSeconds);
}




#pragma mark - 监听视频缓冲和加载状态

- (void)addObserveWithPlayerItem:(AVPlayerItem *)playerItem {
    [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    
    if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        
        NSTimeInterval loadedTime = [self availableDurationWithPlayerItem:playerItem];
        NSTimeInterval totalTime = CMTimeGetSeconds(playerItem.duration);
        
        
    }else if ([keyPath isEqualToString:@"status"]) {
        if (playerItem.status == AVPlayerStatusReadyToPlay) {
            NSLog(@"playitem is ready");
            [self.avPlayer play];
            self.slider.enabled = YES;
        }else if (playerItem.status == AVPlayerStatusUnknown) {
            
        }
    }
    
}


- (void)removeObserverWithPlayerItem:(AVPlayerItem *)playerItem {
    [playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
    [playerItem removeObserver:self forKeyPath:@"status"];
}

#pragma mark - response

- (void)backAction:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - private method

- (void)showOrHideBar {
    
    
    self.topCons.active = NO;
    self.topCons = [self.topView.topAnchor constraintEqualToAnchor:self.view.topAnchor constant:self.isHiddenTabView?0:-60];
    self.topCons.active = YES;
    
    self.bottomCons.active = NO;
    self.bottomCons = [self.bottomView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor constant:self.isHiddenTabView?0:60];
    self.bottomCons.active = YES;
    
    [UIView animateWithDuration:.3 animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        self.isHiddenTabView = !self.isHiddenTabView;
    }];
}
#pragma mark - rotate control

- (BOOL)shouldAutorotate {
    return YES;
}


- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscape;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationLandscapeRight;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
     [self showOrHideBar];
}
@end
